import sys
sys.setrecursionlimit(10000)
def dfs(x, y, x1, y1):
v.add((x, y))
for r, c in [(x - 1, y), (x, y + 1), (x + 1, y), (x, y - 1)]:
if r in range(n) and c in range(m) and (r, c) != (x1, y1) and a[r][c] == a[x][y]:
if (r, c) in v or dfs(r, c, x, y):
return True
return False
n, m = map(int, input().split())
a = [input() for i in range(n)]
v = set()
for i in range(n):
for j in range(m):
if not (i, j) in v and dfs(i, j, -1, -1):
print('Yes')
quit()
print('No')
#include<bits/stdc++.h>
//Every problem is a gift without them we would not grow
//A person who never made a mistake never tried anything new
using namespace std;
typedef long long ll;
bool vis[500][500];
char tab[500][500];
int dx[4]={1,-1,0,0};
int dy[4]={0,0,1,-1};
int n,m;
/*
bool dfs(int i,int j,int pi,int pj)
{
vis[i][j]=true;
for(int c=0;c<4;c++)
{
int dx=i+di[c];
int dy=j+dj[c];
if(dx<0 || dy<0 || dx>n ||dy>m)
continue;
if(t[i][j]!=t[dx][dy])
continue;
if(!vis[dx][dy] && dfs( dx,dy,i,j))
return true;
if(vis[dx][dy] && (dx!=pi || dy!=pj))
return true;
}
return false;
}
bool iscycle()
{
memset(vis,false,sizeof vis);
for(int i=0;i<n;i++)
{
for(int j=0;j<m;j++)
{
if(!vis[i][j])
{
if(dfs(i,j,-1,-1))
return true;
}
}
}
return false;
}
*/
bool dfs(int i, int j, int pi, int pj)
{
vis[i][j]=true;
for (int c=0 ; c<4 ; c++)
{
int di=i+dx[c];
int dj=j+dy[c];
if (di>n || di<0 || dj>m || dj<0)
continue;
if (tab[di][dj] != tab[i][j])
continue;
if (vis[di][dj] && (di!=pi || dj!=pj))
return true;
if (!vis[di][dj] && dfs(di,dj,i,j))
return true;
}
return false;
}
bool iscycle()
{
memset(vis,false,sizeof(vis));
for (int i=0 ; i<n ; i++)
{
for (int j=0 ; j<m ; j++)
{
if (!vis[i][j])
{
if(dfs(i,j,-1,-1))
return true;
}
}
}
return false;
}
int main()
{
cin>>n>>m;
for(int i=0;i<n;i++)
cin>>tab[i];
if(iscycle())
cout<<"Yes";
else
cout<<"No";
return 0;
}
75. Sort Colors | 74. Search a 2D Matrix |
71. Simplify Path | 62. Unique Paths |
50. Pow(x, n) | 43. Multiply Strings |
34. Find First and Last Position of Element in Sorted Array | 33. Search in Rotated Sorted Array |
17. Letter Combinations of a Phone Number | 5. Longest Palindromic Substring |
3. Longest Substring Without Repeating Characters | 1312. Minimum Insertion Steps to Make a String Palindrome |
1092. Shortest Common Supersequence | 1044. Longest Duplicate Substring |
1032. Stream of Characters | 987. Vertical Order Traversal of a Binary Tree |
952. Largest Component Size by Common Factor | 212. Word Search II |
174. Dungeon Game | 127. Word Ladder |
123. Best Time to Buy and Sell Stock III | 85. Maximal Rectangle |
84. Largest Rectangle in Histogram | 60. Permutation Sequence |
42. Trapping Rain Water | 32. Longest Valid Parentheses |
Cutting a material | Bubble Sort |
Number of triangles | AND path in a binary tree |